import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * synchronize与Lock.
 */
public class LockTest {
    private static LockTest lock1 = new LockTest(); // test1的锁
    private static Lock lock3 = new ReentrantLock(false);

    public static void main(String[] args) throws InterruptedException {

        for (int i = 1; i < 20; i++) {
            new Thread(() -> {
                //test();
                //lock1.test1();
                //test2();
                test3();
            }, String.valueOf(i)).start();
        }
    }

    /**
     * 非线程安全.
     */
    public static void test() throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + "==>" + "start");
        Thread.sleep(1);
        System.out.println(Thread.currentThread().getName() + "==>" + "end");

    }

    /**
     * synchronized修饰普通方法
     * 锁为调用此方法对象：lock1
     */
    public synchronized void test1() throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + "==>" + "start");
        Thread.sleep(1);
        System.out.println(Thread.currentThread().getName() + "==>" + "end");
    }

    /**
     * synchronized修饰静态方法
     * 锁为此方法所在Class类：LockTest.class
     */
    public static synchronized void test2() throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + "==>" + "start");
        Thread.sleep(1);
        System.out.println(Thread.currentThread().getName() + "==>" + "end");
    }

    /**
     * 锁为lock3, 这里使用可重入锁ReentrantLock
     */
    public static void test3() {
        try {
            lock3.lock(); // 获取锁
            System.out.println(Thread.currentThread().getName() + "==>" + "start");
            Thread.sleep(1);
            System.out.println(Thread.currentThread().getName() + "==>" + "end");
            System.out.println("------------------");
        } catch (Exception exp) {
            exp.printStackTrace();
        } finally {
            lock3.unlock(); // 释放锁
        }

    }
}
